//
// Created by cjg on 2018/5/29.
// Copyright (c) 2018 chenjg. All rights reserved.
//

#import "CCRequestTool.h"

#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"[文件名:%s]\n" "[函数名:%s]\n" "[行号:%d] \n" fmt), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...);
#endif


static CCRequestTool *instance;


@interface CCRequestTool ()

@end

@implementation CCRequestTool

+ (instancetype)shared {
    if (!instance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[CCRequestTool alloc] init];
        });
    }
    return instance;
}

- (instancetype)init {
    if (self == [super init]) {
        _sessionManager = [CCAFHTTPSessionManager manager];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        self.timeout = 15;
        self.header = @{
                @"Accept": @"application/json",
                @"Content-Type": @"application/x-www-form-urlencoded",
                @"Accept-Language": @"zh-cn",
                @"X-Requested-With": @"XMLHttpRequest"
        };
    };
    return self;
}

- (void)setTimeout:(NSTimeInterval)timeout {
    _timeout = timeout;
    _sessionManager.requestSerializer.timeoutInterval = timeout;
}

- (NSURLSessionDataTask *)requestWithURL:(NSString *)url type:(RequestType)type params:(id)params finish:(RequestFinishBlock)finish {
    return [self requestWithURL:url type:type params:params header:nil upProgress:nil downProgress:nil finish:finish];
}

- (NSURLSessionDataTask *)requestWithURL:(NSString *)url
                                    type:(RequestType)type
                                  params:(id)params
                                  header:(NSDictionary *)header
                              upProgress:(void (^)(NSProgress *))upProgress
                            downProgress:(void (^)(NSProgress *))downloadProgress
                                  finish:(RequestFinishBlock)finish {
    NSDictionary *httpHeader = header;
    if (!httpHeader) {
        httpHeader = _header;
    }
    for (NSString *key in httpHeader.allKeys) {
        [_sessionManager.requestSerializer setValue:httpHeader[key] forHTTPHeaderField:key];
    }
    if (![url hasPrefix:@"http"]) {
        url = [_baseURL stringByAppendingString:url];
    }
    NSURLSessionDataTask *task = [_sessionManager
            cc_ataTaskWithHTTPMethod:type
                           URLString:url
                          parameters:params
                      uploadProgress:upProgress
                    downloadProgress:downloadProgress
                             success:^(NSURLSessionDataTask *task, id responseObjc) {
                                 NSString *jsonString = [self convertToJsonString:responseObjc];
                                 NSLog(@"********************\n请求URL成功: %@,参数： %@", task.currentRequest.URL.absoluteString,params);
                                 finish(true, responseObjc, jsonString, task);
                             }
                             failure:^(NSURLSessionDataTask *task, NSError *error) {
                                 NSLog(@"********************\n请求URL成功: %@,参数： %@", task.currentRequest.URL.absoluteString,params);
                                 finish(false, error, nil, task);
                             }];
    [task resume];
    return task;
}

- (NSURLSessionDataTask *)formDataWithURL:(NSString *)url
                                   params:(id)params
                                   header:(NSDictionary *)header
                                   models:(NSArray<CCNetModel *> *)models
                               upProgress:(void (^)(NSProgress *upProgress))upProgress
                                   finish:(RequestFinishBlock)finish {
    NSDictionary *httpHeader = header;
    if (!httpHeader) {
        httpHeader = _header;
    }
    for (NSString *key in httpHeader.allKeys) {
        [_sessionManager.requestSerializer setValue:httpHeader[key] forHTTPHeaderField:key];
    }
    if (![url hasPrefix:@"http"]) {
        url = [_baseURL stringByAppendingString:url];
    }
    return [_sessionManager POST:url parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
        for (CCNetModel *netModel in models) {
            [netModel addToFormData:formData];
        }
    }                   progress:upProgress success:^(NSURLSessionDataTask *task, id responseObjc) {
        NSString *jsonString = [self convertToJsonString:responseObjc];
        NSLog(@"********************\n请求URL成功: %@,参数： %@", task.currentRequest.URL.absoluteString,params);
        finish(true, responseObjc, jsonString, task);
    }                    failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"********************\n请求URL成功: %@,参数： %@", task.currentRequest.URL.absoluteString,params);
        finish(false, error, nil, task);
    }];
}

- (NSURLSessionDownloadTask *)downLoadWithURL:(NSString *)url
                                      fileURL:(NSString *)fileURL
                                     progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                            completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *task = [_sessionManager downloadTaskWithRequest:request
                                    progress:downloadProgressBlock
                                 destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                     return [NSURL fileURLWithPath:fileURL];
                                 }
                           completionHandler:completionHandler];
    [task resume];
    return task;
}

#pragma mark 私有方法

- (NSString *)convertToJsonString:(id)objc {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:objc options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

@end

